package controller

import (
	"net/http"
	"strconv"
	"test/timer/task"
)

// 任务列表
func List(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/list" && r.URL.Path != "/" {
		http.Error(w, "not found", http.StatusNotFound)
		return
	}

	l := task.List()
	t := tpl("./templates/tasks_list.html")
	data := map[string]interface{}{
		"action": "list",
		"list":   l,
	}
	t.Execute(w, data)
}

// 新增计划任务
func Add(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		r.ParseForm()

		name := r.FormValue("name")
		spec := r.FormValue("spec")
		job := r.FormValue("job")
		status, _ := strconv.Atoi(r.FormValue("status"))

		_, e := task.Add(name, spec, job, status)
		if e != nil {
			err(w, e.Error())
			return
		}

		http.Redirect(w, r, "/list", http.StatusFound)
		return
	}
	data := map[string]interface{}{
		"action": "add",
	}
	t := tpl("./templates/tasks_add.html")
	t.Execute(w, data)
}

// 删除任务
func Del(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	id, _ := strconv.Atoi(r.FormValue("id"))
	e := task.Del(id)
	if e != nil {
		err(w, e.Error())
		return
	}

	http.Redirect(w, r, "/list", http.StatusFound)
}

// 更新状态
func Status(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	id, _ := strconv.Atoi(r.FormValue("id"))
	tag, _ := strconv.Atoi(r.FormValue("tag"))
	e := task.SetStatus(id, tag)
	if e != nil {
		err(w, e.Error())
		return
	}

	http.Redirect(w, r, "/list", http.StatusFound)
}

// 刷新任务
func Flush(w http.ResponseWriter, r *http.Request) {
	task.Flush()
	http.Redirect(w, r, "/list", http.StatusFound)
}
